import domtoimage from 'dom-to-image';
import FileSaver from "file-saver"
import { message } from 'ant-design-vue'
import jsPDF from 'jspdf'

// 导出pdf
export const pageToPDF = async (elementId: string, title: string = "prints", bgColor = "#fff") => {
  let dom = document.getElementById(elementId);
  domtoimage.toPng(dom, { quality: 1, scale: 2 }).then(function (dataUrl) {
    var img = new Image();
    img.src = dataUrl;
    const A4Width = 595.28;
    const A4Height = 841.89;
    img.onload = () => {
      let imgW = img.width*0.95;
      let imgH = img.height*0.9;
      let pageHeight = (imgW / A4Width) * A4Height;
      let imgWidth = A4Width;
      let imgHeight = (A4Width / imgW) * imgH;
      let PDF = new jsPDF("p", 'pt', 'a4');
      if (A4Height > pageHeight) {
        PDF.addImage(dataUrl, "PNG", 0, 0, A4Width, imgHeight);
      } else {
        for (let i = 0; i < Math.ceil(pageHeight / A4Height); i++) {
          PDF.addImage(dataUrl, "PNG", 0, -A4Height * i, A4Width, imgHeight);
          if (i < Math.ceil(pageHeight / A4Height) - 1) {
            PDF.addPage();
            console.log('addPage')
          }
        }
      }
      PDF.save(title + ".pdf");
      message.success('PDF导出成功')
    };
  })
    .catch(function (error) {
      console.error('wrong!', error);
    });
}

// 转成图片
export const pageToImage = async (elementId: string, title: string = "prints", bgColor = "#fff") => {
  let dom = document.getElementById(elementId);
  domtoimage.toPng(dom, { quality: 1, scale: 3 }).then(function (dataUrl) {
    var img = new Image();
    img.src = dataUrl;
    FileSaver.saveAs(dataUrl, title)
    message.success('图片保存成功')
  })
    .catch(function (error) {
      console.error('wrong!', error);
    });
}
